<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2019/3/11
 * Time: 22:00
 */

namespace app\common\pay;

use app\common\lib\Orders;
use Jdpay\HttpUtils;
use Jdpay\XMLUtil;

/**
 * 京东支付
 * Class Jd
 * @package app\pay\controller
 */
class Jd
{
    /**
     *  @param $goods_type //1=>虚拟,2=>实体
     * 生成订单
     * @param $body string 商品名字
     * @param $out_trade_no string 订单号
     * @param $total_amount
     * @return array|bool
     */
    public function pay($body, $out_trade_no, $total_amount,$goods_type = 1)
    {
        $jdConfig = Orders::getPayConfig('jd');


        if ($goods_type == 1)
        {
            $notifyUrl =  $jdConfig['notifyUrl1'];
        }else{
            $notifyUrl =  $jdConfig['notifyUrl2'];
        }

        $data = [
            'version' => $jdConfig['version'],
            'merchant' => $jdConfig['merchant'],
            'tradeNum' => $out_trade_no,
            'tradeName' => $body,
            'tradeTime' => date('YmdHis'),
            'amount' => $total_amount,
            'currency' => $jdConfig['currency'],
            'notifyUrl' => $notifyUrl,
            'ip' => request()->ip(),
            'orderType' => 1,// （0：实物，1：虚拟）
            'userId' => $this->user['id'],// 商户的用户账号，除扫码支付外必传
        ];
        $reqXmlStr = XMLUtil::encryptReqXml($data,$jdConfig);
        $httputil = new HttpUtils();
        list ($return_code, $return_content) = $httputil->http_post_data($jdConfig['uniorderUrl'], $reqXmlStr);

        $flag = XMLUtil::decryptResXml($return_content, $resData,$jdConfig);

        if ($flag && $resData['result']['code'] === '000000' && $resData['result']['desc'] === '成功')
        {
            $signData = md5('merchant=' . $jdConfig['merchant'] . '&orderId=' . $resData['orderId'] . '&key=' . $jdConfig['md5Key']);

            return ['appid' => $jdConfig['appid'], 'merchant' => $jdConfig['merchant'],'order_id' => $out_trade_no, 'orderId' => $resData['orderId'], 'signData' => $signData];
        } else
        {
            return false;
        }
    }
}
